# coding=UTF-8
from django.template import Library, Node, Template, TemplateSyntaxError, Variable
from django.utils.translation import ugettext as u_
from datetime import date, timedelta
from django.conf import settings
# from PythonMagick import Image
from DjoppingMagick import Image
from os import path, makedirs

register = Library()

class ResizedThumbnailNode(Node):
    def __init__(self, filename, width=None, height=None):
        self.image_name = Variable(filename)
        # self.filename = '%s%s' % (settings.MEDIA_ROOT, filename)
        if width:
            self.width = int(width)
        else:
            self.width = 100
        self.height = height

    def render(self, context):
        # The URL to the image file, without the MEDIA_URL.
        image_name = self.image_name.resolve(context).image.split('/')
        # The OS path to the image file.
        filename = str(settings.MEDIA_ROOT + '/'.join(image_name))
        # The OS path to the thumbnail's dir.
        thumb_path = settings.THUMBS_ROOT + str(self.width) + '/'
        # The OS path to the thumbnail.
        thumb_filename = str(thumb_path + image_name[-1:][0])
        # The URL to the thumbnail.
        thumb_url = settings.THUMBS_URL +\
                    str(self.width) + '/' +\
                    image_name[-1:][0]
        if not path.exists(thumb_filename):
            image_file = Image(filename)
            if image_file.size().width() > self.width:
                if not path.exists(thumb_path):
                    makedirs(thumb_path)
                image_file.scale(str(self.width))
                image_file.write(thumb_filename)
            else:
                # If I didn't resize it, then I set the URL to the
                # original image file.
                thumb_url = settings.MEDIA_URL + '/'.join(image_name)
        return thumb_url

def Thumbnail(parser, token):
    bits = token.contents.split()
    if len(bits) == 1:
        raise TemplateSyntaxError, u_(u'thumb recibe al menos un parámetro, el \
                                        nombre del archivo original.')
    dimensions = bits[2].split('x')
    for dim in dimensions:
        try:
            int(dim)
        except:
            raise TemplateSyntaxError, u_(u'Las medidas del thumbnail deben \
                                            proporcionarse en píxels, como \
                                            enteros, sin unidades.')
    if len(dimensions) == 1:
        return ResizedThumbnailNode(bits[1], dimensions[0])
    else:
        return ResizedThumbnailNode(bits[1], dimensions[0], dimension[1])

product_thumbnail = register.tag('thumb', Thumbnail)

